<template>
  <div class="alarm">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>AI告警</span>
        </div>
      </template>
      
      <!-- 筛选条件 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="核查状态">
            <el-select 
              v-model="filterForm.status" 
              placeholder="请选择核查状态" 
              clearable
              style="width: 160px;"
            >
              <el-option label="待核查" value="pending" />
              <el-option label="已核查" value="checked" />
              <el-option label="已忽略" value="ignored" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="预警类型">
            <el-select 
              v-model="filterForm.type" 
              placeholder="请选择预警类型" 
              clearable
              style="width: 160px;"
            >
              <el-option label="人员入侵" value="intrusion" />
              <el-option label="异常行为" value="abnormal" />
              <el-option label="物品遗留" value="abandoned" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="预警时间">
            <el-date-picker
              v-model="filterForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 320px;"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 告警列表 -->
      <div class="alarm-list">
        <el-table 
          :data="alarmList" 
          v-loading="loading" 
          style="width: 100%"
          :fit="true"
        >
          <el-table-column prop="time" label="预警时间" min-width="160" />
          <el-table-column prop="type" label="预警类型" min-width="120" />
          <el-table-column prop="site" label="站点信息" min-width="120">
            <template #default="scope">
              <div>{{ scope.row.site.name }}</div>
              <div class="text-gray">({{ scope.row.site.code }})</div>
            </template>
          </el-table-column>
          <el-table-column prop="device" label="监控设备" min-width="120">
            <template #default="scope">
              <div>{{ scope.row.device.name }}</div>
              <div class="text-gray">({{ scope.row.device.code }})</div>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="位置信息" min-width="160" />
          <el-table-column prop="status" label="核查状态" min-width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="预警截图" min-width="180">
            <template #default="scope">
              <el-image
                style="width: 100px; height: 60px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="200" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button link type="success" @click="handleCheck(scope.row)" v-if="scope.row.status === 'pending'">核查</el-button>
              <el-button link type="info" @click="handleIgnore(scope.row)" v-if="scope.row.status === 'pending'">忽略</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 告警详情弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        title="告警详情"
        width="70%"
        :destroy-on-close="true"
      >
        <div class="alarm-detail" v-if="currentAlarm">
          <div class="detail-content">
            <!-- 左侧基本信息 -->
            <div class="detail-section basic-info">
              <div class="section-header">
                <el-icon><InfoFilled /></el-icon>
                <h4>基本信息</h4>
              </div>
              <div class="section-content">
                <div class="detail-item">
                  <label>预警时间：</label>
                  <span>{{ currentAlarm.time }}</span>
                </div>
                <div class="detail-item">
                  <label>预警类型：</label>
                  <span>{{ currentAlarm.type }}</span>
                </div>
                <div class="detail-item">
                  <label>站点信息：</label>
                  <span>{{ currentAlarm.site.name }} ({{ currentAlarm.site.code }})</span>
                </div>
                <div class="detail-item">
                  <label>监控设备：</label>
                  <span>{{ currentAlarm.device.name }} ({{ currentAlarm.device.code }})</span>
                </div>
                <div class="detail-item">
                  <label>位置信息：</label>
                  <span>{{ currentAlarm.location }}</span>
                </div>
                <div class="detail-item">
                  <label>核查状态：</label>
                  <el-tag :type="getStatusType(currentAlarm.status)">
                    {{ getStatusText(currentAlarm.status) }}
                  </el-tag>
                </div>
                <template v-if="currentAlarm.status === 'checked'">
                  <div class="detail-item">
                    <label>核查时间：</label>
                    <span>{{ currentAlarm.checkTime }}</span>
                  </div>
                  <div class="detail-item">
                    <label>核查结果：</label>
                    <el-tag :type="currentAlarm.checkResult === 'accurate' ? 'success' : 'warning'">
                      {{ currentAlarm.checkResult === 'accurate' ? '预警准确' : '系统误报' }}
                    </el-tag>
                  </div>
                  <div class="detail-item">
                    <label>情况说明：</label>
                    <span>{{ currentAlarm.checkDescription }}</span>
                  </div>
                </template>
              </div>
            </div>

            <!-- 右侧告警记录 -->
            <div class="detail-section alarm-record">
              <div class="section-header">
                <el-icon><VideoCamera /></el-icon>
                <h4>告警记录</h4>
              </div>
              <div class="section-content media-grid">
                <div class="media-section">
                  <div class="media-header">
                    <el-icon><Picture /></el-icon>
                    <span>告警截图</span>
                  </div>
                  <div class="media-content">
                    <el-image
                      :src="currentAlarm.image"
                      :preview-src-list="[currentAlarm.image]"
                      fit="contain"
                      class="alarm-image"
                    />
                  </div>
                </div>
                <div class="media-section" v-if="currentAlarm.video">
                  <div class="media-header">
                    <el-icon><VideoPlay /></el-icon>
                    <span>告警视频</span>
                  </div>
                  <div class="media-content">
                    <video
                      :src="currentAlarm.video"
                      controls
                      class="alarm-video"
                    ></video>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>

      <!-- 核查对话框 -->
      <el-dialog
        v-model="checkDialogVisible"
        title="告警核查"
        width="500px"
        :destroy-on-close="true"
      >
        <el-form
          ref="checkFormRef"
          :model="checkForm"
          :rules="checkFormRules"
          label-width="100px"
        >
          <el-form-item label="核查结果" prop="result">
            <el-radio-group v-model="checkForm.result">
              <el-radio label="accurate">预警准确</el-radio>
              <el-radio label="false">系统误报</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="情况说明" prop="description">
            <el-input
              v-model="checkForm.description"
              type="textarea"
              :rows="4"
              placeholder="请详细描述核查情况..."
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="checkDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitCheck(checkFormRef)">确定</el-button>
      </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
const checkFormRef = ref()
import { ElMessage } from 'element-plus'
import { InfoFilled, VideoCamera, Picture, VideoPlay } from '@element-plus/icons-vue'

// 筛选表单数据
const filterForm = reactive({
  status: '',
  type: '',
  timeRange: []
})

// 列表数据
const loading = ref(false)
const alarmList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗控制
const dialogVisible = ref(false)
const currentAlarm = ref(null)

// 获取告警列表数据
const fetchAlarmList = async () => {
  loading.value = true
  try {
    // TODO: 替换为实际的API调用
    const response = await mockFetchData()
    alarmList.value = response.data
    total.value = response.total
  } catch (error) {
    console.error('获取告警列表失败:', error)
    ElMessage.error('获取告警列表失败')
  } finally {
    loading.value = false
  }
}

// 模拟数据获取
const mockFetchData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 生成模拟数据
      // 站点和摄像头配置
      const siteConfig = [
        {
          name: '主井口监控点',
          code: 'SITE001',
          cameras: [
            { name: '主井口-01', code: 'CAM001' },
            { name: '主井口-02', code: 'CAM002' },
            { name: '主井口-03', code: 'CAM003' },
            { name: '主井口-04', code: 'CAM004' }
          ]
        },
        {
          name: '副井口监控点',
          code: 'SITE002',
          cameras: [
            { name: '副井口-01', code: 'CAM005' },
            { name: '副井口-02', code: 'CAM006' },
            { name: '副井口-03', code: 'CAM007' }
          ]
        },
        {
          name: '井下作业区',
          code: 'SITE003',
          cameras: [
            { name: '井下-01', code: 'CAM008' },
            { name: '井下-02', code: 'CAM009' }
          ]
        },
        {
          name: '地面运输区',
          code: 'SITE004',
          cameras: [
            { name: '运输-01', code: 'CAM010' },
            { name: '运输-02', code: 'CAM011' },
            { name: '运输-03', code: 'CAM012' },
            { name: '运输-04', code: 'CAM013' },
            { name: '运输-05', code: 'CAM014' }
          ]
        }
      ]

      const mockData = Array.from({ length: 10 }, (_, index) => {
        // 随机选择一个站点
        const siteIndex = index % siteConfig.length
        const site = siteConfig[siteIndex]
        
        // 随机选择该站点的一个摄像头
        const cameraIndex = index % site.cameras.length
        const camera = site.cameras[cameraIndex]

        const status = ['pending', 'checked', 'ignored'][index % 3];
        const isChecked = status === 'checked';
        const baseData = {
          id: index + 1,
          time: `2024-03-${19 - (index % 5)} ${10 + (index % 14)}:${30 + (index % 30)}:00`,
          type: ['人员入侵', '异常行为', '物品遗留', '其他'][index % 4],
          site: {
            name: site.name,
            code: site.code
          },
          device: {
            name: camera.name,
            code: camera.code
          },
          location: site.name,
          status: status,
          image: 'https://images.pexels.com/photos/442576/pexels-photo-442576.jpeg',
          video: 'https://www.w3schools.com/html/mov_bbb.mp4'
        };

        if (isChecked) {
          baseData.checkTime = `2024-03-${19 - (index % 5)} ${11 + (index % 14)}:${30 + (index % 30)}:00`;
          baseData.checkResult = ['accurate', 'false'][index % 2];
          baseData.checkDescription = ['现场确认有人员非法闯入，已通知保安处理', '系统误判，为正常施工人员'][index % 2];
        }

        return baseData;
      })

      resolve({
        data: mockData,
        total: 100
      })
    }, 500)
  })
}

// 状态样式
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    checked: 'success',
    ignored: 'info'
  }
  return types[status] || 'default'
}

// 状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待核查',
    checked: '已核查',
    ignored: '已忽略'
  }
  return texts[status] || status
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchAlarmList()
}

// 重置表单
const resetForm = () => {
  filterForm.status = ''
  filterForm.type = ''
  filterForm.timeRange = []
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAlarmList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAlarmList()
}

// 操作处理
const handleView = (row) => {
  currentAlarm.value = row
  dialogVisible.value = true
}

// 核查对话框控制
const checkDialogVisible = ref(false)
const currentCheckAlarm = ref(null)
const checkForm = reactive({
  result: '',
  description: ''
})

// 核查表单规则
const checkFormRules = {
  result: [
    { required: true, message: '请选择核查结果', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请填写情况说明', trigger: 'blur' },
    { min: 5, message: '情况说明至少5个字符', trigger: 'blur' }
  ]
}

const handleCheck = (row) => {
  currentCheckAlarm.value = row
  checkForm.result = ''
  checkForm.description = ''
  checkDialogVisible.value = true
}

const submitCheck = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // TODO: 替换为实际的API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 更新告警数据
        currentCheckAlarm.value.checkResult = checkForm.result
        currentCheckAlarm.value.checkDescription = checkForm.description
        currentCheckAlarm.value.status = 'checked'
        currentCheckAlarm.value.checkTime = new Date().toLocaleString()
        
        ElMessage.success('核查成功')
        checkDialogVisible.value = false
        fetchAlarmList()
      } catch (error) {
        ElMessage.error('核查失败')
      }
    }
  })
}

const handleIgnore = async (row) => {
  try {
    // TODO: 替换为实际的API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('已忽略该告警')
    fetchAlarmList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 初始化加载
fetchAlarmList()
</script>

<style scoped>
.alarm {
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
}

.el-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow: hidden;
}

.filter-container {
  margin-bottom: 16px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.alarm-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-table) {
  flex: 1;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.alarm-detail {
  padding: 20px;
}

.detail-content {
  display: flex;
  gap: 24px;
}

.detail-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.basic-info {
  flex: 0 0 300px;
}

.alarm-record {
  flex: 1;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.section-header .el-icon {
  font-size: 18px;
  color: #409eff;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  width: 80px;
  font-weight: bold;
  color: #606266;
  flex-shrink: 0;
}

.detail-item span {
  flex: 1;
  word-break: break-all;
}

.media-grid {
  display: flex;
  gap: 16px;
}

.media-section {
  background: white;
  border-radius: 6px;
  padding: 16px;
  flex: 1;
}

.media-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #606266;
}

.media-header .el-icon {
  font-size: 16px;
  color: #409eff;
}

.media-content {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f8f9fa;
  border-radius: 4px;
  overflow: hidden;
  height: 240px;
}

.alarm-image,
.alarm-video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style> 